/*
 * @Descripttion:
 * @version:
 * @Author: 淏
 * @Date: 2022-09-28 11:38:44
 * @LastEditors: 淏
 * @LastEditTime: 2023-05-21 10:42:32
 */
export default {
  /**
   * @name: 淏
   * @msg: 根据后端返回的文件流下载Excel文件
   * excel type='application/vnd.ms-excel'
   * zip type='application/zip'
   * @return {*}
   */
  downloadFileBlob(res, fileName, type) {
    const a = document.createElement('a')
    const blob = new Blob([res], {
      type: type,
    })
    const url = URL.createObjectURL(blob)
    a.setAttribute('href', url)
    a.setAttribute('download', fileName)
    a.click()
  },

  /**
   * @name: 淏
   * @msg: 根据后端文件地址下载
   * @return {*}
   */
  downloadFileURL(fileUrl, fileName = new Date().valueOf().toString()) {
    fetch(fileUrl).then((res) =>
      res.blob().then((blob) => {
        let a = document.createElement('a')
        let url = window.URL.createObjectURL(blob)
        a.href = url
        a.download = fileName
        a.click()
        window.URL.revokeObjectURL(url)
      })
    )
  },

  /**
   * @name: 淏
   * @msg: 根据图片地址下载图片
   * @return {*}
   */
  downloadImage(imgUrl, name) {
    var image = new Image()
    // 解决跨域 Canvas 污染问题,
    image.setAttribute('crossorigin', 'anonymous')
    image.onload = function () {
      var canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      var context = canvas.getContext('2d')
      context.drawImage(image, 0, 0, image.width, image.height)
      var url = canvas.toDataURL('image/png') //将图片格式转为base64
      var a = document.createElement('a') // 生成一个a元素
      var event = new MouseEvent('click') // 创建一个单击事件
      a.download = name || 'myPhoto' // 设置图片名称
      a.href = url // 将生成的URL设置为a.href属性
      a.dispatchEvent(event) // 触发a的单击事件
    }
    image.src = imgUrl + '?time=' + Date.now() //注意，这里是灵魂，否则依旧会产生跨域问题
  },
}
